TEST12138

TEST12138

长路漫漫,唯心作伴。

Front-end Basics: Implicit Conversion in JavaScript Addition

Let's do a little test, don't search on Baidu or write code to test.
What is the output of the following:

1 + 1

'1' + 1

1 + true

NaN + 1

NaN + '1'

null + 1

null + '1'

[1] + 1

[1,2] + [1]

[1] + {n : 1}

If you are a bit confused about these operations, then you probably haven't understood implicit type conversion in addition.
What are the rules for addition?
A picture will make it clear.

image

Ok, let's look at an example.

image

Looking at the picture above, let's summarize.
Both sides are primitive types, not strings, so they need to be converted to number types.

image

It's equivalent to 0 + NaN, so the result is NaN.

For example, [1] + 1 from above.

image

It contains an object type, so valueOf is called.

image

After calling valueOf, it's not a primitive type, so toString is called.

image

It has been converted to a primitive type, following the steps above, since it contains a string, everything is converted to a string and added, so the result is '11'.

Let's look at another example.

image

It throws an error here, indicating that it cannot convert this object to a primitive type. This is because valueOf and toString cannot convert obj to a primitive type.

These things often appear in interview questions, testing whether you have a good understanding of the knowledge points. Let's work hard, everyone.

Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.